<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2020/6/8
 * Time: 17:41
 */

namespace app\applet\model;


use think\Db;
use Stbz\Api\SupplyClient;
use think\Exception;

class MyOrder
{
    private $appKey   = 'A855F0BA1EBCD119BEFBDE6EC07ECE65';
    private $appSecret = '68B892679EB78F9FB45ED3D62DE838B7';

    public function __construct()
    {
        vendor("JuHe.autoload");
    }
    /**
     * 我的订单列表数据   type  1=全部  2=待发货  3=待收货  4=待评价 5=退换货 6=已完成
     *          一个订单多个商品的情况下  申请售后和评价都是单个商品操作
     *                              订单商品数据列表中要判断单个商品是否评价  是否申请售后
     *
     *
     */
    public function orderList($member_id,$type,$page,$page_size){

        $where=[];
        $where['o.is_del']=1;
        if($type==1){
           $where['o.status']=['in',[2,3,4,5,6,8,9,10]] ;
        }elseif($type==2){
            $where['o.status']=2;
        }elseif($type==3){
            $where['o.status']=3 ;
        }elseif($type==4){
            $where['o.status']=4 ;
        }elseif($type==5){
            $where['o.status']=['in',[8,9,10]] ;
        }else{
            $where['o.status']=['in',[5,12]] ;
        }

        $field='o.order_id,o.status,o.order_score_money,o.order_coin_money,o.source_type,
        o.store_id,o.goods_class,o.log_sn,o.log_id';
        $data=Db::name('order')->alias('o')
            ->field($field)
            ->where(['o.member_id'=>$member_id])
            ->where($where)
            ->page($page,$page_size)
            ->order("o.order_id desc")
            ->select();

        foreach ($data as &$item){

            $source_type=$item["source_type"];
            if(in_array($source_type,[2,3])){
                $item['company_name']="第三方商城";

            }elseif($source_type==4) {
                $item['company_name']="自营店铺";
            }else
            {
                $item['company_name']=Db::name("store_apply")->where(['sa_id'=>$item['store_id']])->value("company_name");
            }
        }

        $source_type_list=array_column($data,"source_type",'order_id');

        if(!empty($data)){
            foreach($data as $k=>&$v){
                if(in_array($source_type_list[$v['order_id']],[2,3])){//供应链
                    //商品
                    $goods_list=Db::name('order_goods')->alias('og')
                        ->field('og.og_id as order_goods_id,og.goods_id,og.goods_name,og.spec_name,og.spec_id,og.goods_num,og.score_money,og.coin_money,
                    og.delivery_type,og.delivery_fee,g.cover as cover_pic,og.is_comment')
                        ->join('choice_goods g','g.goods_id=og.goods_id')
                        ->where(['og.order_id'=>$v['order_id']])
                        ->select();
                }else{
                    //商品
                    $goods_list=Db::name('order_goods')->alias('og')
                        ->field('og.og_id as order_goods_id,og.goods_id,og.goods_name,og.spec_name,og.spec_id,og.goods_num,og.score_money,og.coin_money,
                    og.delivery_type,og.delivery_fee,g.cover_pic,og.is_comment')
                        ->join('goods g','g.goods_id=og.goods_id')
                        ->where(['og.order_id'=>$v['order_id']])
                        ->select();
                }

                //商品数量
//                $v['goods_number_count']=Db::name('order_goods')
//                    ->where(['order_id'=>$v['order_id']])->count();

                $v['goodsList']=$goods_list;
            }
        }

        $count= Db::name('order')->alias('o')
           // ->join('store_apply sa','sa.sa_id=o.store_id')
            ->where(['o.member_id'=>$member_id])
            ->where($where)
            ->count();

        //待评价的条数
        $comment_count=Db::name('order')
            ->where(['member_id'=>$member_id,'status'=>4])
            ->count();

        $list['current_page'] = $page;
        $list['total_page'] =ceil($count / $page_size);
        $list['page_num'] = $page_size;
        $list['total_num'] = $count;
        $list['comment_count'] = $comment_count;
        $list['data'] = $data;

        return $list;
    }

    /**
     * 我的订单详情
     *
     */
    public function orderDetail($member_id,$order_id){
        $source_type=Db::name("order")
            ->where(['order_id'=>$order_id,'member_id'=>$member_id])
            ->value("source_type");
        if(in_array($source_type,[2,3])){
            $field='o.order_id,o.order_sn,o.create_time,og.og_id as order_goods_id,og.goods_name,og.goods_num,
        og.score_money,og.coin_money,og.spec_name,og.spec_pic,g.source,o.status,o.pay_time,og.after_status,
        og.og_d_status,og.spec_id,o.log_id,o.log_sn';
        }else{
            $field='o.order_id,o.order_sn,o.create_time,og.og_id as order_goods_id,og.goods_name,og.goods_num,
        og.score_money,og.coin_money,og.spec_name,og.spec_pic,o.store_id,o.status,o.pay_time,og.after_status,
        og.og_d_status,og.spec_id,o.log_id,o.log_sn';
        }

        $where=[];
        $where['o.pay_status']=2;

        if(in_array($source_type,[2,3])){

            $data=Db::name('order_goods')->alias('og')
                ->field($field)
                ->join('order o','o.order_id=og.order_id')
                ->join('choice_goods g','g.goods_id=og.goods_id')
                ->where(['o.member_id'=>$member_id,'o.order_id'=>$order_id])
                ->where($where)
                ->select();
            //dump(Db::name('order_goods')->getLastSql());

            foreach ($data as &$item){
                if($item['source']==2){
                    $item['company_name']='京东';
                }elseif($item['source']==6){
                    $item['company_name']='阿里巴巴';
                }elseif($item['source']==7){
                    $item['company_name']='天猫商城';
                }else{
                    $item['company_name']='第三方商城';
                }
                //申请售后时间
                $after=Db::name('order_after_sale')
                    ->where(['order_id'=>$item['order_id']])->find();
                if(!empty($after)){
                    $item['apply_time']=$after['create_time'];
                    $item['after_score_money']=$item['score_money'];
                    $item['after_coin_money']=$item['coin_money'];
                }else{
                    $item['apply_time']=0;
                }

                //物流状态最新时间
                $item['latest_time']=0;

                unset($item['source']);
            }
        }else{

            $data=Db::name('order_goods')->alias('og')
                ->field($field)
                ->join('order o','o.order_id=og.order_id')
                ->where(['o.member_id'=>$member_id,'o.order_id'=>$order_id])
                ->where($where)
                ->select();
            //dump(Db::name('order_goods')->getLastSql());
            foreach ($data as &$item){
                if($item['store_id']>0){
                    $item['company_name']=Db::name('store_apply')
                        ->where('sa_id',$item['store_id'])->value('company_name');
                }else{
                    $item['company_name']='自营店铺';
                }

                //申请售后时间
                $after=Db::name('order_after_sale')
                    ->where(['order_id'=>$item['order_id']])->find();
                if(!empty($after)){
                    $item['apply_time']=$after['create_time'];
                    $item['after_score_money']=$item['score_money'];
                    $item['after_coin_money']=$item['coin_money'];
                }else{
                    $item['apply_time']=0;
                }

                //物流状态最新时间
                $item['latest_time']=0;

            }
        }


        return $data;
    }

    /**
     * 查看订单商品数据   type=1评价  2=售后
     */
    public function selectOrderOne($order_id,$member_id,$type,$order_goods_id=0){
        $source_type=Db::name("order") ->where(['member_id'=>$member_id,'order_id'=>$order_id])->value("source_type");
        if($type==2) {

            $field='o.order_id,og.goods_id,og.goods_name,og.spec_name,og.goods_num,og.score_money,og.coin_money,og.spec_pic';
            //商品
            $data = Db::name('order_goods')->alias('og')
                ->field($field)
                ->join('order o', 'o.order_id=og.order_id')
                ->where(['og.og_id' => $order_goods_id,'o.member_id'=>$member_id])
                ->find();

        }else {
           if(in_array($source_type,[2,3])){//供应链
               $field = 'o.order_id,og.og_id as order_goods_id,og.goods_name,og.goods_num,
        og.score_money,og.coin_money,og.spec_name,g.cover cover_pic';
               $data = Db::name('order_goods')->alias('og')
                   ->field($field)
                   ->join('order o', 'o.order_id=og.order_id')
                   ->join('choice_goods g', 'g.goods_id=og.goods_id')
                   ->where(['o.member_id' => $member_id, 'o.order_id' => $order_id, 'og.og_id' => $order_goods_id])
                   ->find();
               $data['company_name']="第三方商城";
           }elseif($source_type==4){//干货分享
               $field = 'o.order_id,og.og_id as order_goods_id,og.goods_name,og.goods_num,
        og.score_money,og.coin_money,og.spec_name,g.cover_pic';
               $data = Db::name('order_goods')->alias('og')
                   ->field($field)
                   ->join('order o', 'o.order_id=og.order_id')
                   ->join('goods g', 'g.goods_id=og.goods_id')
                   ->where(['o.member_id' => $member_id, 'o.order_id' => $order_id, 'og.og_id' => $order_goods_id])
                   ->find();
               $data['company_name']="自营店铺";
           }else{
               $field = 'o.order_id,sa.company_name,og.og_id as order_goods_id,og.goods_name,og.goods_num,
        og.score_money,og.coin_money,og.spec_name,g.cover_pic';
               $data = Db::name('order_goods')->alias('og')
                   ->field($field)
                   ->join('order o', 'o.order_id=og.order_id')
                   ->join('store_apply sa', 'sa.sa_id=o.store_id')
                   ->join('goods g', 'g.goods_id=og.goods_id')
                   ->where(['o.member_id' => $member_id, 'o.order_id' => $order_id, 'og.og_id' => $order_goods_id])
                   ->find();
           }

        }
        return $data;

    }

    /**
     * 删除订单,确认收货  type 1=删除  2=确认收货
     */
    public function updateOrder($order_id,$member_id,$data,$type=1){
        if(empty($data['spec_id'])){
            //判断订单是否只有一种商品
            $nums= Db::name('order_goods')
                ->where(['order_id'=>$order_id])->count();
            if($nums==1){
                $spec_id=Db::name('order_goods')
                    ->where(['order_id'=>$order_id])->value("spec_id");
            }else{
                returnJson(-2004,'商品规格ID不能为空');
            }
        }else{
            $spec_id=$data['spec_id'];
        }
        if($type==1){
            $info['status']=$data['status'];
            $info['is_del']=$data['is_del'];
            $info['update_time']=$data['update_time'];
        }else{
            $info['status']=$data['status'];
            $info['update_time']=$data['update_time'];
        }

//        dump($info);
//        dump($spec_id);
//        dump($member_id);
        Db::startTrans();
        try{
            $num=Db::name('order')
                ->where(['member_id'=>$member_id,'order_id'=>$order_id])
                ->update($info);
            if($num===false){
                throw new Exception("操作失败1");
//                returnJson(-2004,'操作失败1');
            }
            if($type==2){//确认收货
                $num2=Db::name('order_goods')
                    ->where(['order_id'=>$order_id,'spec_id'=>$spec_id])
                    ->update(['confirm_time'=>time(),'is_recevied'=>1]);
                if($num2===false){
                    throw new Exception("操作失败2");
//                    returnJson(-2004,'操作失败2');
                }
                //更新订单状态
                $goodsList=Db::name("order_goods")
                    ->where(['order_id'=>$order_id])
                    ->field("is_recevied")->select();
                $isReceived=true;
                foreach ($goodsList as $ogoods){
                    if($ogoods['is_recevied']!=1){//未收货 未评价
                        $isReceived=false;
                    }
                }
                //确认收货
                if($isReceived){
                    //dump($isReceived);
                    $num3=Db::name('order')->where(['order_id'=>$order_id,'member_id'=>$member_id])
                        ->update(['status'=>4]);
                    if($num3===false){
                        throw new Exception("更新失败");
//                        returnJson(-2004,'更新失败');
                    }
                }else{
                    Db::name('order')->where(['order_id'=>$order_id,'member_id'=>$member_id])
                        ->update(['status'=>11]);
                }
            }
            Db::commit();
            return true;
        }catch (Exception $e){

            Db::rollback();
            //return false;
            returnJson(-2004,'操作失败3');
        }
    }

    /**
     * 订单评价提交
     */
    public function comment($member_id,$data){

        $order=Db::name('order')->where('order_id',$data['order_id'])->find();
        $order_goods=Db::name('order_goods')->where('og_id',$data['order_goods_id'])->find();

        $info['member_id']=$member_id;
        $info['order_id']=$data['order_id'];
        $info['star']=$data['star'];
        $info['content']=$data['content'];
        $info['order_goods_id']=$data['order_goods_id'];
        $info['goods_id']=$order_goods['goods_id'];
        $info['store_id']=$order['store_id'];
        $info['order_sn']=$order['order_sn'];
        $info['create_time']=time();

        $comment=Db::name('comment')
            ->where(['order_goods_id'=>$data['order_goods_id'],'member_id'=>$member_id])
            ->find();
        if(empty($comment)){
            Db::name('comment')->insert($info);
            //修改订单评价状态
            $count=Db::name('order_goods')->where('order_id',$data['order_id'])->count();
            if($count<2){
                Db::name('order')->where('order_id',$data['order_id'])->update(['status'=>5]);
            }else{
                //修改order_goods的评价状态
                Db::name('order_goods')->where('og_id',$data['order_goods_id'])->update(['is_comment'=>2]);

                $test=Db::name('order_goods')
                    ->field('og_id,is_comment')
                    ->where('order_id',$data['order_id'])
                    ->select();
                $test_count=Db::name('order_goods')
                    ->field('og_id,is_comment')
                    ->where('order_id',$data['order_id'])
                    ->count();
                $a=0;
                foreach ($test as $k=>$v){
                    if($v['is_comment']==2){
                        $a=$a+1;
                    }
                }
                if($test_count==$a){
                    Db::name('order')->where('order_id',$data['order_id'])->update(['status'=>5]);
                }
            }
        }

        return true;
    }


    /**
     * 订单评价详情
     */
    public function commentDetail($member_id,$data,$current_page,$page_num){
        $info['member_id']=$member_id;
        //获取订单来源
        $source_type=Db::name("order")
            ->where(['order_id'=>$data['order_id'],'member_id'=>$info['member_id']])
            ->value("source_type");

        if(in_array($source_type,[2,3])){
            $commentList=Db::name('comment')
                ->alias("c")
                ->field("c.reply store_reply,c.star,c.content,g.source,og.goods_num,og.spec_name,og.score_money,og.coin_money,og.spec_pic,og.goods_name")
                ->join("mm_order_goods og","c.order_id=og.order_id and c.goods_id=og.goods_id")
                ->join("mm_choice_goods g","og.goods_id=g.goods_id")
                ->where(['c.goods_id'=>$data['goods_id'],'c.member_id'=>$member_id,'c.order_id'=>$data['order_id']])
                ->page($current_page,$page_num)
                ->select();
               foreach ($commentList as &$comment){
                   if($comment['source']==2){
                       $comment['company_name']='京东';
                   }elseif($comment['source']==6){
                       $comment['company_name']='阿里巴巴';
                   }elseif($comment['source']==7){
                       $comment['company_name']='天猫商城';
                   }else{
                       $comment['company_name']='第三方商城';
                   }
                   unset($comment['source']);
               }
        }else{
            $order_one=Db::name("order")
                ->where(['order_id'=>$data['order_id'],'member_id'=>$member_id])->find();

            $field='c.reply store_reply,c.star,c.content,og.goods_num,og.spec_name,
            og.score_money,og.coin_money,og.spec_pic,og.goods_name';
            $commentList=Db::name('comment')->alias("c")
                ->field($field)
                ->join("order_goods og","c.order_id=og.order_id and c.goods_id=og.goods_id")
                //->join("order o","o.order_id=c.order_id")
                ->where(['c.goods_id'=>$data['goods_id'],'c.member_id'=>$member_id,'c.order_id'=>$data['order_id']])
                ->page($current_page,$page_num)
                ->select();

            //dump(Db::name('comment')->getLastSql());

            foreach ($commentList as &$comment){
                if($order_one['store_id']>0){
                    $comment['company_name']=Db::name('store_apply')
                        ->where('sa_id',$order_one['store_id'])->value('company_name');
                }else{
                    $comment['company_name']='自营店铺';
                }
            }
        }


        $total_num=Db::name('comment')
            ->alias("c")
            ->where(['c.goods_id'=>$data['goods_id'],'c.member_id'=>$member_id,'c.order_id'=>$data['order_id']])
            ->count();

        $list['current_page'] = $current_page;
        $list['total_page'] = ceil($total_num / $page_num);
        $list['page_num'] = $page_num;
        $list['total_num'] = $total_num;
        $list['data'] = $commentList;
        return $list;
    }

    /**
     * 售后提交
     */
    public function afterSalesPost($member_id,$data){

        $order=Db::name('order')->where('order_id',$data['order_id'])->find();
        $order_sn=get_order1(2,1,$member_id);
        $info['member_id']=$member_id;
        $info['order_id']=$data['order_id'];
        $info['after_type']=$data['after_type'];
        $info['order_goods_id']=$data['order_goods_id'];
        $info['store_id']=$order['store_id'];
        $info['after_reason']=$data['after_reason'];
        $info['after_sn']=$order_sn;
        $info['create_time']=time();
        $info['order_status']=$order['status'];//保存订单申请售后之前的状态
        if(isset($data['content'])&& !empty($data['content'])){
            $info['content']=$data['content'];
        }

        //收货地址
        if(isset($data['receiver'])&& !empty($data['receiver'])){
            $info['receiver']=$data['receiver'];
        }
        if(isset($data['re_phone'])&& !empty($data['re_phone'])){
            $info['re_phone']=$data['re_phone'];
        }
        if(isset($data['address'])&& !empty($data['address'])){
            $info['address']=$data['address'];
        }

        if(empty($data['spec_id'])){
            $nums=Db::name("order_goods")->where(['order_id'=>$data['order_id']])->count();
            if($nums==1){
                $spec_id=Db::name("order_goods")->where(['order_id'=>$data['order_id']])->value("spec_id");
            }else{
                returnJson(-2004,"商品规格ID不能为空");
            }
        }else{
            $spec_id=$data['spec_id'];
        }
        //查询售后商家处理时间
        $expire_day=Db::name('system_config')->where('field_name','after_expire_day')->value('field_value');
        $info['end_time']=time()+$expire_day*24*3600;//12*86400=1036800

        //删除取消售后的数据
        Db::name('order_after_sale')
            ->where(['member_id'=>$member_id,'order_id'=>$data['order_id'],'status'=>4])
            ->delete();

        $comment=Db::name('order_after_sale')
//            ->where(['order_goods_id'=>$data['order_goods_id'],'member_id'=>$member_id])
            ->where(['order_id'=>$data['order_id'],'member_id'=>$member_id])
            ->find();
        if(empty($comment)){
            //供应链
            if(in_array($order['source_type'],['2,3'])){
                //获取当前规格价格
                $method = 'POST';//请求方法
                $action = '/v2/afterSale/beforeCheck';//请求资源名
                $this->client = new SupplyClient( $this->appKey, $this->appSecret);
                //dump($this->client );
                $param['orderSn'] = $order['order_sn'];
                $param['sku'] = intval($spec_id);

                $response = $this->client->getApiResponse($method,$action,$param);
                //dump($response);
                $response = json_decode($response,true);
                $refund=false;
                //dump($response);
                if($response['code']==1){//接口请求成功
                    $rst=$response['data'];
                    $num=$rst['num'];
                    $serviceType=$rst['serviceType'];
                    if($num==0&&$serviceType[0]['code']==40&&$info['after_type']==1){//只退款
                        $serviceTypeCode=40;
                        $refund=true;
                    }elseif($serviceType[0]['code']==50&&$info['after_type']==2){//退货退款
                        $serviceTypeCode=50;
                        $refund=true;
                    }else{
                        returnJson(-2004,"状态异常");
                    }
                }else{
                    returnJson(-2004,$response['msg']);
                }

            }
            Db::startTrans();
            try{
                Db::name('order_after_sale')->insert($info);

                //-----------------------修改订单状态（面对多个商品的订单，是否需要在订单商品中加一个字段判断）-----------------
                if($data['after_type']==1){
                    Db::name('order')->where('order_id',$data['order_id'])->update(['status'=>8]);
                }else{
                    Db::name('order')->where('order_id',$data['order_id'])->update(['status'=>9]);

                }
                if(in_array($order['source_type'],['2,3'])){
                    if($refund){//退货退款
                        if($info['after_type']==1){//只退款
//                            $method = 'POST';//请求方法
//                            $action = '/v2/afterSale';//请求资源名
//                            $this->client = new SupplyClient( $this->appKey, $this->appSecret);
//                            //期望退还运费logisticFee 单位分
//                            $param=['orderSn'=> $order['order_sn'],'sku'=>$spec_id,'num'=>0,'logisticFee'=>1000,
//                                'serviceTypeCode'=>$serviceTypeCode];
//                            //returnTypeCode
//                            $response = $this->client->getApiResponse($method,$action,$param);
//                            $response = json_decode($response,true);
                        }else{//退货退款

                        }
                    }else{
                        throw  new  Exception("提交失败");
                    }
                }
                Db::commit();

                return true;

            }catch (Exception $e){
               Db::rollback();
                returnJson(-2004,'操作失败');
            }
        }


    }

    /**
     * 售后查看详情
     */
    public  function  afterDetail($member_id,$order_id){
        $source_type=Db::name("order")->where(['order_id'=>$order_id,'member_id'=>$member_id])->value("source_type");
        if(in_array($source_type,[2,3])){//供应链
            $field2='og.goods_name,og.spec_name,og.goods_num,og.score_money,og.coin_money,g.cover cover_pic';
        }else{
            $field2='og.goods_name,og.spec_name,og.goods_num,og.score_money,og.coin_money,g.cover_pic';
        }
        $field='o.order_score_money,o.order_coin_money,oas.order_id,oas.oas_id,oas.after_type,oas.after_reason,oas.after_sn,oas.status,oas.create_time,oas.end_time';


        $data=Db::name('order_after_sale')->alias('oas')
            ->field($field)
            ->join('order o','o.order_id=oas.order_id')
            ->where(['oas.member_id'=>$member_id,'o.order_id'=>$order_id])
            ->find();
        if(in_array($source_type,[2,3])){
            $goods_list=Db::name('order_goods')->alias('og')
                ->field($field2)
                ->join('choice_goods g','g.goods_id=og.goods_id')
                ->where(['og.order_id'=>$order_id])
                ->select();
        }else{
            $goods_list=Db::name('order_goods')->alias('og')
                ->field($field2)
                ->join('goods g','g.goods_id=og.goods_id')
                ->where(['og.order_id'=>$order_id])
                ->select();
        }

        $data['goods_list']=$goods_list;

        return $data;
    }

    /**
     * 提醒发货
     */
    public function remind($member_id,$order_id){
        $source_type=Db::name("order")
            ->where(['order_id'=>$order_id,'member_id'=>$member_id])
            ->value("source_type");
        if(!in_array($source_type,[2,3])) {
            $order=Db::name('order')
                ->where('order_id',$order_id)
                ->find();
            if($order['store_id']>0){
                $store_id=Db::name('store_apply')->where('sa_id',$order['store_id'])->value('member_id');
            }else{
                $store_id=0;
            }
            $data['create_time']=time();
            $data['member_id']=$member_id;
            $data['title']='订单发货提醒';
            $data['content']='您有一条待发货的订单，请尽快处理！';
            $data['object_type']=2;
            $data['object_arr']=$store_id;
            $data['class_type']=13;
            Db::name('message')->insert($data);
        }


        return true;
    }

    /**
     * 取消退款
     */
    public function afterRefund($member_id,$order_id,$order_goods_id){
        $one=Db::name('order_after_sale')
            ->where(['member_id'=>$member_id,'order_id'=>$order_id,'order_goods_id'=>$order_goods_id])
            ->find();
        //dump($one);exit;
        Db::name('order_after_sale')
            ->where(['member_id'=>$member_id,'order_id'=>$order_id,'order_goods_id'=>$order_goods_id])
            ->update(['status'=>4,'update_time'=>time()]);
        Db::name('order')
            ->where(['member_id'=>$member_id,'order_id'=>$order_id])
            ->update(['status'=>$one['order_status'],'update_time'=>time()]);

        return true;
    }

}

